package com.stone.activeMQ.subscriber;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author Stone
 * @date 2020/4/4 13:57
 * activeMQ发布订阅模式
 */
public class Consumer {
    private static final String USERNAME= ActiveMQConnection.DEFAULT_USER; // 默认的连接用户名
    private static final String PASSWORD=ActiveMQConnection.DEFAULT_PASSWORD; // 默认的连接密码
    private static final String BROKEURL=ActiveMQConnection.DEFAULT_BROKER_URL; // 默认的连接地址


    public static void main(String[] args) {
        //连接工厂
        ConnectionFactory connectionFactory;
        //连接
        Connection connection = null;
        //会话
        Session session;
        //目的地，即消息队列（MQ）
        Destination destination;
        //消费者
        MessageConsumer messageConsumer;

        //1.连接到activeMQ
        connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEURL);

        try{
            //2.通过工厂创建连接
            connection = connectionFactory.createConnection();
            //3.开启连接
            connection.start();
            //4.通过连接获取session对象,三种策略
            //Session.AUTO_ACKNOWLEDGE:自动确认，搭配recive()
            //Session.CLIENT_ACKNOWLEDGE:客户通过消息的 acknowledge 方法确认消息
            //Session.DUPS_ACKNOWLEDGE:该选择只是会话迟钝的确认消息的提交
            session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
            //5.通过session创建队列
            destination = session.createTopic("创建话题");
            //6.通过session创建消费者
            messageConsumer = session.createConsumer(destination);

            //7.接收消息
            messageConsumer.setMessageListener(new MyMessageListener());


            //8.提交session
            session.commit();

        }catch (Exception e){
            e.printStackTrace();
        }
//        finally {
//            if(connection!=null){
//                try {
//                    connection.close();
//                } catch (JMSException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//
//        }

    }
}